package com.google.bartenderserver;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.*;
import android.os.*;
import java.net.*;
import java.io.*;
import android.util.*;

import java.util.*;

public class BartenderServerActivity extends Activity {

    //private TextView serverStatus;

    // default ip
    public static String SERVERIP = "10.0.2.15";

    // designate a port
    public static final int SERVERPORT = 8080;

    private Handler handler = new Handler();

    private ServerSocket serverSocket;
    
    private String[] bottleNames = {"Gin", "Rum", "Vodka"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.backdrop);
        //serverStatus = (TextView) findViewById(R.id.server_status);

        // Set listener for title bar changes. HACK!
        Stage stage = (Stage) findViewById(R.id.stage);
        stage.setListener(this);
        
        SERVERIP = getLocalIpAddress();

        Thread fst = new Thread(new ServerThread());
        fst.start();
    }

    public class ServerThread implements Runnable {

        public void run() {
            try {
                if (SERVERIP != null) {
                    handler.post(new Runnable() {
                        public void run() {
                            setTitle("Listening for device connection...");
                        }
                    });
                    serverSocket = new ServerSocket(SERVERPORT);
                    while (true) {
                        // listen for incoming clients
                        Socket client = serverSocket.accept();
                        handler.post(new Runnable() {
                            public void run() {
                               setTitle("Connected. Ready...");
                            }
                        });

                        try {
                            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                            String line = null;
                            while ((line = in.readLine()) != null) {
                                Log.d("ServerActivity", line);
                                final String msg = line;
                                handler.post(new Runnable() {
                                    public void run() {
                                    	String type = msg.substring(0, 1);
                                    	if(type.equalsIgnoreCase("x"))
                                    	{
                                    		
                                    	}
                                    	else if(type.equalsIgnoreCase("s"))
                                    	{
                                    		setTitle("Shaking...");
                                    		Stage stage = (Stage) findViewById(R.id.stage);
                                			stage.devStartShake();
                                    	}
                                    	else if(type.equalsIgnoreCase("p"))
                                    	{
                                    		setTitle("Putting drink on bar...");
                                    		Stage stage = (Stage) findViewById(R.id.stage);
                                			stage.devPutAway();
                                    	}                                    	
                                    	else
                                    	{
                                    		String value = msg.substring(1);
                                    		if(type.equalsIgnoreCase("i"))
                                    		{
                                    			int bottle = Integer.parseInt(value);
                                    			Stage stage = (Stage) findViewById(R.id.stage);
                                    			stage.setItem(bottle);
                                    			setTitle("Selected '"+bottleNames[bottle]+"'");
                                    		}
                                    		else
                                    		{
                                    			int direction = Integer.parseInt(value);
                                    			if(direction == 6) { // Downwards
	                                        		setTitle("Pouring...");
	                                    			Stage stage = (Stage) findViewById(R.id.stage);
	                                    			
	                                    			stage.devStartPour();
                                    			}
                                    			
                                    		}
                                    	}
                                    }
                                });
                            }
                            break;
                        } catch (Exception e) {
                            handler.post(new Runnable() {
                                public void run() {
                            		setTitle("Connection interrupted");
                                    //serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                                }
                            });
                            e.printStackTrace();
                        }
                    }
                } else {
                    handler.post(new Runnable() {
                        public void run() {
                        	setTitle("Couldn't detect internet");
                           // serverStatus.setText("Couldn't detect internet connection.");
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                       setTitle("Error");
                    }
                });
                e.printStackTrace();
            }
        }
    }

    // gets the ip address of your phone's network
    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
                }
            }
        } catch (SocketException ex) {
            Log.e("ServerActivity", ex.toString());
        }
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
             // make sure you close the socket upon exiting
             serverSocket.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == 47)
		{
			Stage stage = (Stage) findViewById(R.id.stage);
			stage.devStartShake();
		}
		if(keyCode == 48)
		{
			Stage stage = (Stage) findViewById(R.id.stage);
			stage.devShowGrid();
		}
		if(keyCode == 49)
		{
			Stage stage = (Stage) findViewById(R.id.stage);
			stage.devStartPour();
		}
		if(keyCode == 50)
		{
			Stage stage = (Stage) findViewById(R.id.stage);
			stage.devPutAway();
		}		
		else
		{
			Log.d("keypress", ""+keyCode);
		}
		
		return super.onKeyDown(keyCode, event);
	}
}